<!-- 角色管理 -->
<template>
    <div class="common-layout">
        <el-backtop :bottom="50" target=".main" ref="backTop" :visibility-height="10"></el-backtop>
        <el-container>
            <el-header>
                <!-- 表单组件 -->
                <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm">
                    <el-space>
                        <el-form-item prop="name" label="角色名称：">
                            <el-input class="fix_input" v-model.trim="ruleForm.name" type="text" autocomplete="off"
                                placeholder="请输入角色名称" />
                        </el-form-item>
                        <el-form-item prop="desc" label="描述信息：">
                            <el-input class="fix_input" v-model.trim="ruleForm.desc" type="text" autocomplete="off"
                                placeholder="请输入描述信息" clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-button :icon="Plus" type="primary" @click="addRole(ruleFormRef)">添加</el-button>
                        </el-form-item>
                    </el-space>
                </el-form>
            </el-header>
            <el-main>
                <div class="el-scrollbar__wrap metaBox">
                    <el-backtop :bottom="100" ref="backTop" :visibility-height="5" target=".metaBox .el-scrollbar__wrap" />
                    <!-- 表格组件 -->
                    <el-table :data="tableData" border style="width: 100%;height: 100%;" class="scrollbar-demo-item">
                        <el-table-column prop="name" label="角色名称" />
                        <el-table-column prop="desc" label="说明" />
                        <el-table-column label="操作">
                            <template #default="scope">
                                <div v-if="scope.row.id !== 1">
                                    <el-button type="primary"
                                        @click="handleEdit(scope.$index, scope.row); dialogVisible1 = true">修改</el-button>
                                    <el-button type="primary"
                                        @click="handleEmpower(scope.$index, scope.row);">授权</el-button>
                                    <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-main>
            <el-footer>
                <Paging v-bind="pagination" @page-change="pageChange" />
            </el-footer>
        </el-container>
    </div>

    <!-- 对话框组件 -->
    <el-dialog v-model="dialogVisible1" title="修改信息" width="60%" :before-close="handleClose">
        <!-- 修改功能表单组件 -->
        <el-form ref="ruleFormRef2" :model="ruleForm2" status-icon :rules="rules" class="demo-ruleForm">
            <el-space>
                <el-form-item prop="name" label="角色名称：">
                    <el-input class="fix_input" v-model.trim="ruleForm2.name" type="text" autocomplete="off"
                        placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item prop="desc" label="描述信息：">
                    <el-input class="fix_input" v-model.trim="ruleForm2.desc" type="text" autocomplete="off"
                        placeholder="请输入描述信息" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="updataRole(ruleFormRef2);">修改</el-button>
                </el-form-item>
            </el-space>
        </el-form>
    </el-dialog>

    <!-- 授权功能树形组件 -->
    <el-dialog v-model="dialogVisible2" title="权限配置" width="50%" :before-close="handleClose" destroy-on-close>
        <el-tree ref="treeRef" :data="treeData" show-checkbox node-key="id" highlight-current :accordion="true"
            :expand-on-click-node="true" v-loading="Loading" element-loading-text="正在查询中">
            <template #default="{ node, data }">
                <span>{{ node.label }}</span>
                <span v-if="!data.children" class="treechile">{{ data.id }}</span>
            </template>

        </el-tree>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible2 = false">取消</el-button>
                <el-button type="primary" @click="permissionSet();">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { ElMessageBox, type FormInstance } from 'element-plus'
import { post } from '@/utils/http';
import { nextTick, onMounted, reactive, ref } from 'vue';
import { Plus } from '@element-plus/icons-vue'
import Paging from '@/components/paging/Paging.vue'
import { ClassPagination } from '#/index';
import { ElMessage, ElTree } from "element-plus"
import type Node from 'element-plus/es/components/tree/src/model/node'

// 数据初始化
onMounted(() => {
    init()
})

// 控制对话框组件的显示隐藏
const dialogVisible1 = ref(false)
const dialogVisible2 = ref(false)
const Loading = ref(false)
const backTop = ref()                                   //回到顶部
const pagination = reactive(new ClassPagination())      //分页
let tableData: TypeRole[] = reactive([])            //表格数据
let treeData: TypeSystemPermission[] = reactive([])     //树形菜单数据
let treeRef = ref()         //获取权限树

// 授权信息需要的数据
let roleSetPermission = reactive({
    roleId: 0,
    permissions: []
})
const updataRoleId = ref()             //要修改的id

// 定义User数据类型
interface User {
    desc: string,
    gmtCreate: string,
    gmtUpdate: string,
    id: number,
    name: string,
    status: string,
}

const ruleFormRef = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()

//子传父的自定义事件
function pageChange(e: TypePage) {
    pagination.page = e.page
    pagination.limit = e.limit
    init()
}

// 设置表单验证规则
function validateRolename(rule: object, value: string, callback: any) {
    if (value === '') {
        callback(new Error('请输入角色名称'))
    } else {
        callback()
    }
}

// 表单数据绑定
const ruleForm = reactive({
    name: '',
    desc: ''
})
const ruleForm2 = reactive({
    name: '',
    desc: '',
    status: 1,
    id: 0
})

// 绑定表单验证规则与验证方式
const rules = reactive({
    name: [{ validator: validateRolename, trigger: 'blur' }]
})
/**
 * 获取初始化数据，用于渲染页面
 */
function init() {
    const { page, limit } = pagination
    // 接口需要的数据data
    let data = {
        _gp: 'admin.role',
        _mt: 'list',
        limit,
        page
    }
    post(data).then(res => {
        // console.log(res);

        let { data: { total, items },errno } = res
        if (200 === errno) {
            pagination.total = total
            tableData.length = 0;
            tableData.push(...items)

            nextTick(() => {
                backTop.value.$el.click?.()
            })
        }
    }).catch(err => {
        console.log(err);
    })
}

/**
 * 获取修改前的数据
 * @param index 当前下标
 * @param row 当前下标的数据
 */
function handleEdit(index: number, row: User) {
    console.log(row)
    ruleForm2.name = row.name
    ruleForm2.desc = row.desc
    ruleForm2.id = row.id
}
/**
 * 获取授权信息
 * @param index 当前下标
 * @param row 当前下标的数据
 */
function handleEmpower(index: number, row: User) {
    dialogVisible2.value = true
    Loading.value = true
    console.log(treeRef.value,);
    console.log(index, row)
    let data = {
        _gp: 'admin.role',
        _mt: 'permissionList',
        roleId: row.id
    }
    post(data).then(res => {
        console.log(res);
        let { data,errno } = res
        if (200 === errno) {           
            let { systemPermissions, assignedPermissions } = data           
            treeRef.value.setCheckedKeys(assignedPermissions)              
            treeData = systemPermissions
            roleSetPermission.roleId = row.id           //设置授权信息时需要
            Loading.value = false
        }
    }).catch(err => {
        console.log(err);
    })

}
/**
 * 删除功能
 * @param index 当前下标
 * @param row 当前下标的数据
 */
function handleDelete(index: number, row: User) {
    console.log(index, row)

    let data = {
        _gp: 'admin.role',
        _mt: 'delete',
        roleId: row.id
    }

    ElMessageBox.confirm('真的要删除吗？')
        .then(() => {
            post(data).then(res => {
                // console.log(res);
                let { errno } = res
                if (200 === errno) {
                    ElMessage.success("删除成功！")
                    init()
                }
            }).catch(err => {
                console.log(err);
            })
        })
        .catch(() => {
            ElMessage.error("取消删除！")
        })
}


/**
 * 添加角色
 * @param formEl 表单验证结果
 */

function addRole(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let data = {
                _gp: 'admin.role',
                _mt: 'create',
                role: JSON.stringify(ruleForm)
            }
            post(data).then(res => {
                // console.log(res);
                let { errno } = res
                if (200 === errno) {
                    ElMessage.success("添加成功！")
                    init()
                }else{
                    ElMessage.error("数据已存在，无法添加！")
                }
                resetForm(formEl)
            }).catch(err => {
                console.log(err);
                
            })

        } else {
            return false
        }
    })
}

/**
 * 修改
 * @param formEl 表单验证结果
 */

function updataRole(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let data = {
                _gp: 'admin.role',
                _mt: 'update',
                role: JSON.stringify({
                    ...ruleForm2,
                    status: 1
                })
            }
            post(data).then(res => {
                // console.log(res);
                let { errno } = res
                if (200 === errno) {
                    dialogVisible1.value = false
                    ElMessage.success("修改成功！")
                    init()
                }
                resetForm(formEl)
            }).catch(err => {
                console.log(err);
            })

        } else {

            return false
        }
    })
}

/**
 * 进行授权
 */
function permissionSet() {
    roleSetPermission.permissions = treeRef.value.getCheckedKeys(true)
    let data = {
        _gp: "admin.role",
        _mt: "permissionSet",
        roleSetPermissionDTO: JSON.stringify(roleSetPermission),
    }
    post(data).then(res => {
        console.log(res);
        let { errno } = res
        if (200 === errno) {
            dialogVisible2.value = false
            ElMessage.success("授权成功！")
            init()
        }
    }).catch(err => {
        console.log(err);
    })
}

/**
 * 表单重置
 * @param formEl 表单验证结果
 */
function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.resetFields()
}

/**
 * 对话框组件的关闭
 * @param formEl 表单验证结果
 */
function handleClose(done: () => void) {
    done()
}
</script>
  

<style scoped lang="less">
.scrollbar-demo-item {
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
}

.metaBox {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60vh;
    text-align: center;
}

.fix_input {
    width: 200px;
}

.treechile {
    position: relative;
    right: 0px;
    color: red;
}
</style>